import 'package:binggo_bomb/commons/Constants.dart';
import 'package:binggo_bomb/page/card/CardListWidget.dart';
import 'package:binggo_bomb/utils/localStorage.dart';
import 'package:flutter/material.dart';

class CardIndexWidget extends StatefulWidget {
  const CardIndexWidget({super.key});

  @override
  State<CardIndexWidget> createState() => _CardIndexWidgetState();
}

class _CardIndexWidgetState extends State<CardIndexWidget> with SingleTickerProviderStateMixin {

  /// 已选中颜色
  int selectedColor = 0;
  List<Map> nums = [];

  late TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: Constants.tabsColor.length, vsync: this);
    initCardNums();
    super.initState();
  }


  @override
  void didUpdateWidget(CardIndexWidget oldWidget) {
    print("CardIndexWidget  didUpdateWidget");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BingGo Card', style: TextStyle(color: Colors.black87),),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        centerTitle: true,
        actions: <Widget>[
          IconButton(
              icon: const Icon(Icons.add, color: Colors.black87,),
              tooltip: 'liked_widget_bloc',
              onPressed: () {
                addCard();
                // listState.currentState?.changeName("西安${DateTime.now().microsecondsSinceEpoch}");
              }),
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          TabBar(
            labelStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            unselectedLabelStyle: const TextStyle(fontSize: 16),
            isScrollable: false,
            controller: tabController,
            labelColor: Colors.blue,
            indicatorWeight: 3,
            indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
            unselectedLabelColor: Colors.grey,
            indicatorColor: Colors.orangeAccent,
            tabs: Constants.tabsName.map((e) => Tab(text: e,)).toList(),
            onTap: (v) {
              setState(() {
                selectedColor = v;
              });
              // getRadios(tabs[v]["code"].toString(), false);
              // _pageController.jumpToPage(v);
            },
          ),

          Expanded(
              child: TabBarView(
                physics: NeverScrollableScrollPhysics(),//viewPage禁止左右滑动
                controller: tabController,
                // children: [],
                children: Constants.tabsColor.map((e) => CardListWidget(color: int.parse(e), nums: this.nums[int.parse(e)], delCard: delCard)).toList(),
              )
          ),


        ],
      ),
      // body: BodyTabWidget(),
    );
  }



  /// 初始化卡片数字
  initCardNums() {
    this.nums = [];
    for(String i in Constants.tabsColor) {
      Map res = getCardNums(int.parse(Constants.tabsColor[int.parse(i)]));
      setState(() {
        this.nums.add(res);
      });
    }
  }


  /// 获取卡片数据
  Map getCardNums(int color) {
    Map res = {};
    switch(color) {
      case 0: /// "红色"
        res = LocalStorage.getKey<Map>('pinkCards') != null ? LocalStorage.getKey<Map>('pinkCards') as Map : {};
        break;
      case 1: /// "蓝色"
        res = LocalStorage.getKey<Map>('blueCards') != null ? (LocalStorage.getKey<Map>('blueCards') as Map) : {};
        break;
      case 2: /// "黄色"
        res = LocalStorage.getKey<Map>('yellowCards') != null ? LocalStorage.getKey<Map>('yellowCards') as Map : {};
        break;
      case 3: /// "紫色"
        res = LocalStorage.getKey<Map>('purpleCards') != null ? LocalStorage.getKey<Map>('purpleCards') as Map : {};
        break;
      default: /// "红色"
        res = LocalStorage.getKey<Map>('pinkCards') != null ? LocalStorage.getKey<Map>('pinkCards') as Map : {};
        break;
    }
    return res;
  }

  /// 设置卡片数据
  void setCardNums(int color, Map nums) {
    switch(color) {
      case 0: /// "红色"
        LocalStorage.set<Map>('pinkCards', nums);
        break;
      case 1: /// "蓝色"
        LocalStorage.set<Map>('blueCards', nums);
        break;
      case 2: /// "黄色"
        LocalStorage.set<Map>('yellowCards', nums);
        break;
      case 3: /// "紫色"
        LocalStorage.set<Map>('purpleCards', nums);
        break;
      default:
        break;
    }
  }

  /// 添加卡片
  addCard() {
    print("添加卡片");
    List<int> newNums = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,];
    Map res = getCardNums(selectedColor);
    String maxKey = getMaxKey(res.keys);
    res[maxKey] = newNums;
    setCardNums(selectedColor, res);
    initCardNums();
  }

  /// 删除卡片
  delCard(String key) {
    print("正在删除第$key张券");
    Map res = getCardNums(selectedColor);
    res.remove(key);
    setCardNums(selectedColor, res);
    initCardNums();
    Navigator.pop(context);
  }

  /// 获取Card当前最大key
  getMaxKey (Iterable keys) {
    if(keys.length>=1) {
      List list = keys.toList();
      list.toList().sort((a, b) => int.parse(a).compareTo(int.parse(b)));
      return (int.parse(list.last) + 1).toString();
    } else {
      return "1";
    }

    // int i = 0;
    // keys.getRange(start, end)
    // for(int k = 0;k < keys.length; k++) {
    //
    // }
  }
}
